/**
 * 
 */
package com.yuyi.lwq.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.wxpay.sdk.WXPayConstants.SignType;
import com.github.wxpay.sdk.WXPayUtil;
import com.yuyi.lwq.wxpay.PayConfig;

/**
 *
 * @author 李文庆
 * 2018年7月26日 下午5:33:37
 */
@RestController
@RequestMapping("/weixin")
public class NotifyController {
	
	private Logger logger = LoggerFactory.getLogger(NotifyController.class);
	
	@PostMapping("/notifyurl")
	public String notifyUrl(HttpServletRequest request) throws Exception{
		
		/**获取微信后台通知结果*/
		InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result  = new String(outSteam.toByteArray(),"utf-8");
        Map<String, String> map = WXPayUtil.xmlToMap(result);
        logger.info("异步通知：{}",map);
        /**定义返给微信后台的成功字段*/
    	Map<String,String> res = new HashMap<String, String>();
        res.put("return_code", "SUCCESS");
        res.put("return_msg", "OK");
        String resStr = WXPayUtil.mapToXml(res);
        
        /**通过返回的信息里是否有“req_info”来判断是付款还是退款*/
        String req_info = map.get("req_info");
        
        /**1、没有req_info，则是付款*/
        if (Objects.equals(req_info, null)) {
        	
        	/**校验签名是否正确*/
            boolean is = WXPayUtil.isSignatureValid(map,PayConfig.KEY,SignType.HMACSHA256);
            if (Objects.equals(is,true)) {
            	logger.info("签名正确");
        		 /**获取标识*/
                //String attach = map.get("attach");
                //订单状态更新
            }else{
            	logger.info("签名不正确");
                 
                return resStr;
            }
        }
        
        /**2、有req_info则是退款*/
       if (!Objects.equals(req_info, null)) {
        	/*
	        String req_info_Str = map.get("req_info");
	        String key = EncryptAndDecryptTools.StrToBase64Str(WXPayUtil.MD5(PayConfig.KEY).toLowerCase());
	        String decrypt = EncryptAndDecryptTools.decrypt(req_info_Str, key);
	           	
	        Map<String, String> xmlToMap = WXPayUtil.xmlToMap(decrypt);
	        System.out.println(xmlToMap);*/
            
	        return resStr;
        }
        
        return resStr;
        
	}
	
}
